//
//  ZCAddNewAddressVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/2/27.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "ZCAddNewAddressVC.h"

#import "ZCAddNewAddressInputCell.h"
#import "ZCAddNewAddressFootView.h"
#import "ZCAddNewAddressNoticeCell.h"

#import "ZCOrderCheckLeftAndSwitchCell.h"
#import "ZCAreaVC.h"
#import "ZCAddressModel.h"
#import "ZCAddressViewModel.h"
#import "ZCOrderCheckAutoAddressCell.h"
#import "WZGAddressUploadIdentityCell.h"
#import "ZCOrderViewModel.h"
#import <MJExtension.h>
#import <LCActionSheet.h>
#import "SKBaseWebService.h"



typedef NS_ENUM(NSUInteger, ZCAddNewAddressVCSection) {
    ZCAddNewAddressVCSection_BaseInfo,
    ZCAddNewAddressVCSection_IdentiCard,
    ZCAddNewAddressVCSection_SetDefault,
    ZCAddNewAddressVCSection_Count
};

typedef NS_ENUM(NSUInteger, ZCAddNewAddressVCRowIdentiCard) {
    ZCAddNewAddressVCRowIdentiCard_Notice,
    ZCAddNewAddressVCRowIdentiCard_File,
    ZCAddNewAddressVCRowIdentiCard_RealeName,
    ZCAddNewAddressVCRowIdentiCard_IdNum,
    ZCAddNewAddressVCRowIdentiCard_Count
};


@interface ZCAddNewAddressVC () <ZCAddNewAddressInputCellDelegate,UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, copy) NSArray *staticTips;
@property (nonatomic, copy) NSArray *placeholdstrs;
@property (nonatomic, strong) ZCAddressModel *model;

@property (assign, nonatomic) BOOL isLeftUp;//是否上传证明身份证
@property (nonatomic, copy) NSString *oldFontPicStr; //已经存在的身份证
@property (nonatomic, copy) NSString *oldBackPicStr; //已经存在的back身份证

@property (assign, nonatomic) BOOL isOcr;//是否正在识别


@end

@implementation ZCAddNewAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.navTitle = @"收货地址";
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = UIColorFromRGB(0xf4f4f4);
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCAddNewAddressInputCell" bundle:nil] forCellReuseIdentifier:@"ZCAddNewAddressInputCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckLeftAndSwitchCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderCheckLeftAndSwitchCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCAddNewAddressNoticeCell" bundle:nil] forCellReuseIdentifier:@"ZCAddNewAddressNoticeCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckAutoAddressCell" bundle:nil]
         forCellReuseIdentifier:@"ZCOrderCheckAutoAddressCell"];

    [self.tableView registerNib:[UINib nibWithNibName:@"WZGAddressUploadIdentityCell" bundle:nil]
         forCellReuseIdentifier:@"WZGAddressUploadIdentityCell"];

    self.isLeftUp = YES;
    
    UIView *headerView = [[UIView alloc] initWithFrame:(CGRect){0,0,[UIScreen mainScreen].bounds.size.width,60}];
    UINib *nib = [UINib nibWithNibName:@"ZCAddNewAddressFootView" bundle:nil];
    ZCAddNewAddressFootView *view = [nib instantiateWithOwner:self options:nil].firstObject;
    view.frame = headerView.bounds;
    view.btnColor = [UIColor redColor];
    [view addTarget:self action:@selector(saveBtnClickAction) title:@"保存"];
    [headerView addSubview:view];
    self.tableView.tableFooterView = headerView;
    
    if (self.dict == nil) {
        self.model = [[ZCAddressModel alloc] init];
        self.model.is_default = @"1";
    } else {
        self.model = [ZCAddressModel mj_objectWithKeyValues:self.dict];
        self.oldFontPicStr = self.model.id_card_front;
        self.oldBackPicStr = self.model.id_card_back;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

// MARK: - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ZCAddNewAddressVCSection_Count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == ZCAddNewAddressVCSection_BaseInfo) {
        return 5;
    }
    if (section == ZCAddNewAddressVCSection_IdentiCard) {
        if (self.isNormal) { //常规的
            return 0;
        } else {
            return ZCAddNewAddressVCRowIdentiCard_Count;
        }
    }
    if (section == ZCAddNewAddressVCSection_SetDefault) {
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    __weak typeof(self) weakSelf = self;
    if (section == ZCAddNewAddressVCSection_BaseInfo) {
        if (row == 0) {
            ZCOrderCheckAutoAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckAutoAddressCell"
                                                                                forIndexPath:indexPath];
            [cell setEndInputCallback:^(NSString * _Nonnull addres) {
                [weakSelf netAutoCheckAddressWithInputTxt:addres];
            }];
            return cell;
        }
        
        ZCAddNewAddressInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCAddNewAddressInputCell"
                                                                         forIndexPath:indexPath];
        cell.delegate = self;
        NSArray *tips = self.staticTips[section];
        cell.keystr = tips[row - 1];
        
        NSArray *ps = self.placeholdstrs[section];
        cell.placeholdstr = ps[row - 1];
        cell.indexPath = indexPath;
        cell.delegate = self;
        cell.keyboardType = UIKeyboardTypeDefault;
        cell.type = ZCAddNewAddressInputCellType_Input;
        if (row == 1) {
            cell.valuestr = self.model.name;
        }
        if (row == 2) {
            cell.keyboardType = UIKeyboardTypePhonePad;
            cell.valuestr = self.model.phone;
        }
       
        if (row == 3) {
            cell.type = ZCAddNewAddressInputCellType_Select;
            if (self.model.province != nil) {
                NSString *district = self.model.district;
                if (self.model.county.length > 0) {
                    district = self.model.county;
                }
                NSString *area = [NSString stringWithFormat:@"%@%@%@",self.model.province,self.model.city,district];
                cell.valuestr = area;
            }
        }
        if (row == 4) {
            cell.valuestr = self.model.address;
        }
        return cell;
    }
    
    if (section == ZCAddNewAddressVCSection_IdentiCard) {
        if (row == ZCAddNewAddressVCRowIdentiCard_File) {
            __weak typeof(self) weakSelf = self;
            WZGAddressUploadIdentityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WZGAddressUploadIdentityCell"
                                                                                 forIndexPath:indexPath];
            cell.leftURL = self.model.id_card_front;
            cell.rightURL = self.model.id_card_back;
            
            [cell setLeftBtnClickCallback:^{
                weakSelf.isLeftUp = YES;
                [weakSelf showAlbumSheet];
            }];
            [cell setRightBtnClickCallback:^{
                weakSelf.isLeftUp = NO;
                [weakSelf showAlbumSheet];
            }];
            return cell;
        }
        if (row == ZCAddNewAddressVCRowIdentiCard_Notice) {
            ZCAddNewAddressNoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCAddNewAddressNoticeCell"
                                                                              forIndexPath:indexPath];
            return cell;
        }
        if (row == 2 || row == 3) {
            ZCAddNewAddressInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCAddNewAddressInputCell"
                                                                             forIndexPath:indexPath];
            NSArray *tips = self.staticTips[section];
            cell.delegate = self;
            cell.type = ZCAddNewAddressInputCellType_Input;
            cell.keystr = tips[row - 2];
            cell.indexPath = indexPath;
            cell.userInteractionEnabled = NO;
            NSArray *ps = self.placeholdstrs[section];
            cell.placeholdstr = ps[row - 2];
            
            if (row == ZCAddNewAddressVCRowIdentiCard_RealeName) {
                cell.valuestr = self.model.real_name;
            }
            if (row == ZCAddNewAddressVCRowIdentiCard_IdNum) {
                cell.valuestr = self.model.id_card;
                cell.length = 18;
            }
            return cell;
        }
        return nil;
    }
    
    if (section == ZCAddNewAddressVCSection_SetDefault) {
        ZCOrderCheckLeftAndSwitchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckLeftAndSwitchCell"
                                                                              forIndexPath:indexPath];
        NSArray *tips = self.staticTips[section];
        cell.keystr = tips[row];
        cell.isOn = [self.model.is_default boolValue];
        __weak typeof(self) weakSelf = self;
        
        [cell setSwitchOnCallBack:^(BOOL isDefault) {
            weakSelf.model.is_default = @(isDefault).stringValue;
        }];
        return cell;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *v = [UIView new];
    v.backgroundColor = UIColorFromRGB(0xf8f8fc);
    return v;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    if (section == ZCAddNewAddressVCSection_BaseInfo) {
        if (row == 0) {
            return 75.0f;
        }
    }
    if (section == ZCAddNewAddressVCSection_IdentiCard) {
        if (row == ZCAddNewAddressVCRowIdentiCard_File) {
            return 150.0f;
        }
        return 45.0f;
    }
    return 45.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 15;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    if (section == ZCAddNewAddressVCSection_SetDefault) {
        self.model.is_default = @(!self.model.is_default.boolValue).stringValue;
        [self.tableView reloadData];
    }
}

// MARK: - ZCAddNewAddressInputCellDelegate

- (void)addNewAddressInputCellInputAction:(NSIndexPath *)indexPath content:(NSString *)content {
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    if (section == ZCAddNewAddressVCSection_BaseInfo) {
        if (row == 1) {
            self.model.name = content;
        }
        if (row == 2) {
            self.model.phone = content;
        }
        if (row == 4) {
            self.model.address = content;
        }
    }
    if (section == ZCAddNewAddressVCSection_IdentiCard) {
        if (row == ZCAddNewAddressVCRowIdentiCard_RealeName) {
            self.model.real_name = content;
        }
        if (row == ZCAddNewAddressVCRowIdentiCard_IdNum) {
            self.model.id_card = content;
        }
    }
    
    [self.tableView reloadData];
}

- (void)addNewAddressInputCellSelectAction:(NSIndexPath *)indexPath {
    NSInteger secion = indexPath.section;
    NSInteger row = indexPath.row;
    if (secion == ZCAddNewAddressVCSection_BaseInfo) {
        if (row == 3) {        
            [self showAreaVC];
        }
    }
    [self.tableView reloadData];
}

- (void)showAreaVC {
    self.definesPresentationContext = YES;
    ZCAreaVC* areaVC = [[ZCAreaVC alloc] init];
    [areaVC setModalPresentationStyle:UIModalPresentationOverCurrentContext];
    areaVC.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    __weak typeof(self) weakSelf = self;
    [areaVC setSelectedAddressCallBack:^(NSArray * _Nonnull dicts) {
        NSDictionary *pri = dicts.firstObject;
        weakSelf.model.province_code = [pri valueForKey:@"id"];
        weakSelf.model.province = [pri valueForKey:@"name"];
        
        NSDictionary *city = dicts[1];
        weakSelf.model.city_code = [city valueForKey:@"id"];
        weakSelf.model.city = [city valueForKey:@"name"];
        
        NSDictionary *area = dicts.lastObject;
        weakSelf.model.county_code = [area valueForKey:@"id"];
        weakSelf.model.county = [area valueForKey:@"name"];

        [weakSelf.tableView reloadData];
    }];
    [self.view.window.rootViewController presentViewController:areaVC animated:YES completion:^{
        [UIView animateWithDuration:0.3 animations:^{
            areaVC.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        }];
    }];
}

// MARK: - Action

- (void)showAlbumSheet {
    __weak typeof(self) weakSelf = self;
    LCActionSheet *sheet = [[LCActionSheet alloc] initWithTitle:nil cancelButtonTitle:@"取消" clicked:^(LCActionSheet *actionSheet, NSInteger buttonIndex) {
        if (buttonIndex == 1) { //拍照
            [self showCamera:^(NSMutableArray *result) {
                weakSelf.isOcr = YES;
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (weakSelf.isLeftUp) {
                        weakSelf.model.id_card_front = result.firstObject;
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            [weakSelf netPostFileInfo2ORCWithImgURL:weakSelf.model.id_card_front isFront:YES];
                        });
                    } else {
                        weakSelf.model.id_card_back = result.firstObject;
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            [weakSelf netPostFileInfo2ORCWithImgURL:weakSelf.model.id_card_back isFront:NO];
                        });
                    }
                });
            }];
        }
        if (buttonIndex == 2) { //相册
            self.tzvc = nil;
            self.tzvc.maxImagesCount = 1;
            self.tzvc.allowPickingVideo = YES;
            [self showAlbum:^(NSMutableArray *result) {
                weakSelf.isOcr = YES;
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (weakSelf.isLeftUp) {
                        weakSelf.model.id_card_front = result.firstObject;
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            [weakSelf netPostFileInfo2ORCWithImgURL:weakSelf.model.id_card_front isFront:YES];
                        });
                    } else {
                        weakSelf.model.id_card_back = result.firstObject;
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            [weakSelf netPostFileInfo2ORCWithImgURL:weakSelf.model.id_card_back isFront:NO];
                        });
                    }
                });
            }];
        }
    } otherButtonTitles:@"拍照",@"相册选择", nil];
    sheet.buttonFont = [UIFont systemFontOfSize:15 weight:UIFontWeightThin];
    [sheet show];
}

- (void)saveBtnClickAction {
    if (self.isOcr) {
        return;
    }
    [self.view endEditing:YES];
    if (self.model.id_card == nil) {
        self.model.id_card = @"";
    }
    if (self.model.name == nil || self.model.name.length == 0) {
        [self.view makeToast:@"请输入收货人姓名" duration:2.0 position:CSToastPositionCenter];
        return;
    }
    if (self.model.phone == nil || self.model.phone.length == 0) {
        [self.view makeToast:@"请输入手机号" duration:2.0 position:CSToastPositionCenter];
        return;
    }

    if (!self.isNormal) {
        if(self.model.id_card_front == nil ||self.model.id_card_front.length == 0) {
            [self.view makeToast:@"请上传身份证人像面" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        if(self.model.id_card_back == nil ||self.model.id_card_back.length == 0) {
            [self.view makeToast:@"请上传身份证国徽面" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        
        if (![self.model.name isEqualToString:self.model.real_name]) {
            [self.view makeToast:@"收货人姓名和身份证真实姓名必须一致" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        if(!(self.model.id_card.length == 15 || self.model.id_card.length == 18)) {
            [self.view makeToast:@"身份证号有误,请重新上传清晰的身份证" duration:2.0 position:CSToastPositionCenter];
            return;
        }
    }
    [self netSaveNewAddress];
}

// MARK: - NET

- (void)netPostFileInfo2ORCWithImgURL:(NSString *)imgurl isFront:(BOOL)front {
    __weak typeof(self) weakSelf = self;
    NSString *kfront = front ? @"front" :@"back";
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:imgurl forKey:@"id_card"];
    [parameters setValue:kfront forKey:@"side"];
    [SKBaseWebService postRequest:@"/v1/member-address/id-card-ocr" parameters:parameters progress:nil success:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        weakSelf.isOcr = NO;
        if (status == kHXSNoError) {
            if (front) {
                NSDictionary *dict = [data valueForKey:@"ocr_format"];
                NSString *real_name = [dict valueForKey:@"real_name"];
                NSString *id_card_no = [dict valueForKey:@"id_card_no"];
                if (id_card_no == nil
                    || id_card_no.length == 0
                    || real_name == nil
                    || real_name.length == 0) {
                    [weakSelf.view makeToast:@"身份证识别失败,请重新上传清晰照片" duration:2.0 position:CSToastPositionCenter];
                    weakSelf.model.id_card_front = weakSelf.oldFontPicStr;
                    return;
                }
                weakSelf.model.real_name = real_name;
                weakSelf.model.id_card = id_card_no;
            } else {
                NSDictionary *ocr_format = [data valueForKey:@"ocr_format"];
                NSString *issue_org = [ocr_format valueForKey:@"issue_org"];
                if (nil == issue_org || issue_org.length == 0) {
                    [weakSelf.view makeToast:@"身份证识别失败,请重新上传清晰照片" duration:2.0 position:CSToastPositionCenter];
                    weakSelf.model.id_card_back = weakSelf.oldBackPicStr;
                    return;
                }
            }
            [weakSelf.tableView reloadData];
        } else if (status == kHXSInvalidTokenError) {
//            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
//            [vc setGoodsVCCallBack:^(NSInteger type) {
//                
//            }];
//            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
//            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
//            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:msg duration:2.0 position:CSToastPositionCenter];
        }
    } failure:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        [weakSelf.view makeToast:msg duration:2.0 position:CSToastPositionCenter];
    }];
}

- (void)netSaveNewAddress {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCAddressViewModel saveAreaListWithAddress:self.model complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            [weakSelf.view makeToast:@"保存成功" duration:2.0 position:CSToastPositionCenter];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (weakSelf.editCallback) {
                    NSDictionary *dict = [self.model mj_keyValues];
                    weakSelf.editCallback(dict);
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        } else if (status == kHXSInvalidTokenError) {
//            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
//            [vc setGoodsVCCallBack:^(NSInteger type) {
//                if (type == 0) {
//                    [weakSelf.navigationController popViewControllerAnimated:YES];
//                }
//            }];
//            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
//            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
//            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netAutoCheckAddressWithInputTxt:(NSString *)address {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCOrderViewModel autoCheckAddressWithString:address complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            weakSelf.model = [ZCAddressModel mj_objectWithKeyValues:data];
            weakSelf.model.name = weakSelf.model.real_name;
            weakSelf.model.real_name = nil;
            [weakSelf.tableView reloadData];
        } else if (status == kHXSInvalidTokenError) {
//            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
//            [vc setGoodsVCCallBack:^(NSInteger type) {
//                [weakSelf netAutoCheckAddressWithInputTxt:address];
//            }];
//            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
//            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
//            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

// MARK: - GET

- (NSArray *)staticTips {
    if (_staticTips == nil) {
        _staticTips = @[@[@"收货人",@"手机号码",@"选择地址",@"详细地址"],@[@"真实姓名",@"身份证号"],@[@"设置为默认地址"]];
    }
    return _staticTips;
}

- (NSArray *)placeholdstrs {
    if (_placeholdstrs == nil) {
        _placeholdstrs = @[@[@"请输入收货人姓名",@"请输入手机号",@"请选择省市区",@"请输入详细地址"],@[@"请输入真实姓名",@"跨境商品请输入身份证号"]];
    }
    return _placeholdstrs;
}


@end
